home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17746 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.3 KB  |  68 lines

  1. Path: news.mira.net.au!news
  2. From: davidw@werple.net.au (David White)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Recursive CONSTRUCTOR allowed?
  5. Date: 17 Apr 1996 20:29:27 +1000
  6. Organization: Werple Internet, Melbourne
  7. Message-ID: <4l2h67$dfd@werple.net.au>
  8. References: <4l1ck5$pit@falcon.ccs.uwo.ca>
  9. NNTP-Posting-Host: werplez.mira.net.au
  10.  
  11. Sharon Wang <swang1@julian.uwo.ca> writes:
  12.  
  13. >I'd like to implement the following algorithm using constructor
  14. >(I am TOLD to do so)
  15.  
  16. >// create an n linked list
  17. >create node(n)
  18. >{
  19. >    if (n = 0) then
  20. >        reach the length, don't create!
  21. >    else
  22. >        create this node;
  23. >        create node(n-1);
  24. >        make link;
  25. >    end if
  26. >    return;
  27. >}
  28.  
  29. >(1) FIrst of all, does this make sense?
  30.  
  31. I think so.
  32.  
  33. >(2) Is is possible to use constructor instead of member function?
  34.  
  35. Yes, if I understand the problem correctly.
  36.  
  37. >Any suggestion + plus small piece of code is highly appreciated.
  38.  
  39. class Node
  40. {
  41. public:
  42.     Node(int n);
  43.     //...
  44.  
  45. private:
  46.     Node *next;
  47. };
  48.  
  49. Node::Node(int n)
  50. {
  51.   next = (n > 0) ? new Node(n-1) : 0;
  52. }
  53.  
  54. void f()
  55. {
  56.   Node list(3);
  57. }
  58.  
  59. Here, 'f' creates a forward-linked list of four nodes.  Strictly speaking,
  60. the constructor isn't recursive because it is being called for a different
  61. object each time, but it does recursively create new objects. 
  62.  
  63. >Sharon
  64. ><swang1@julian.uwo.ca>
  65.  
  66. David White
  67. davidw@werple.mira.net.au
  68.